package com.wunong.smart.address.starter.converter;

import com.wunong.smart.address.client.vo.AddressVO;
import com.wunong.smart.address.domain.UserAddressDomain;
import com.wunong.smart.address.starter.infrastructure.po.UserAddressPO;
import com.wunong.smart.domain.platform.entify.User;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author create by zealot.zt
 */
public final class UserAddressConverter {

    public static UserAddressDomain toDomain(UserAddressPO po) {
        if (po == null) {
            return null;
        }

        UserAddressDomain domain = UserAddressDomain.of();

        domain.init(po);

        domain.setUser(User.of(po.getUserId(), po.getUserRole()));
        domain.setAddressVO(AddressVO.of(po.getNationCode(), po.getProvinceCode(),
                po.getCityCode(), po.getAreaCode(), po.getRoadCode(), po.getAddress()));
        domain.setIsDefault(po.getIsDefault());
        domain.setMobile(po.getMobile());
        domain.setName(po.getName());
        domain.setValid(Boolean.TRUE.equals(po.getValid()));
        domain.setSex(po.getSex());
        domain.setDescription(po.getDescription());

        return domain;
    }

    public static List<UserAddressDomain> toDomain(List<UserAddressPO> pos) {
        if (CollectionUtils.isEmpty(pos)) {
            return null;
        }

        return pos.stream().map(UserAddressConverter::toDomain)
                .collect(Collectors.toList());
    }

    public static UserAddressPO toPo(UserAddressDomain domain) {
        if (domain == null) {
            return null;
        }

        UserAddressPO po = UserAddressPO.of();

        po.init(domain);

        po.setUserId(domain.getUser().getIdLong());

        AddressVO addressVO = domain.getAddressVO();
        if (Objects.nonNull(addressVO)) {
            po.setNationCode(addressVO.getNationCode());
            po.setProvinceCode(addressVO.getProvinceCode());
            po.setCityCode(addressVO.getCityCode());
            po.setAreaCode(addressVO.getAreaCode());
            po.setRoadCode(addressVO.getRoadCode());
            po.setAddress(addressVO.getAddress());
        }

        po.setIsDefault(domain.getIsDefault());
        po.setMobile(domain.getMobile());
        po.setName(domain.getName());
        po.setSex(domain.getSex());
        po.setValid(domain.isValid());
        po.setDescription(domain.getDescription());

        return po;
    }

    private UserAddressConverter() {
    }

}
